package com.ruoyi.web.admin.data.utils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author 10100
 * @license (C) Copyright 2020-2050,  Corporation Limited.
 * @contact wang.he@cpe-smartcity.com
 * @date 2025-06-09 15:58
 * @description 通用工具类
 */
public class CommonUtils {

    // 上次生成时间
    private static LocalDateTime lastTime = LocalDateTime.now();
    // 循环计数器
    private static int cycleNumber = 0;

    public static synchronized String generateSerialNumber() {
        LocalDateTime now = LocalDateTime.now();

        // 如果进入下一秒，重置计数器
        if (now.isAfter(lastTime.plusSeconds(1)) || now.isBefore(lastTime)) {
            cycleNumber = 0;
        }

        // 更新最后生成时间
        lastTime = now;

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String formattedDate = formatter.format(now);

        // 格式化四位循环数并递增
        String cycleStr = String.format("%04d", cycleNumber);
        // 超过9999归零
        cycleNumber = (cycleNumber + 1) % 10000;

        return formattedDate + cycleStr;
    }

    public static String getCurrentTimestamp() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        return now.format(formatter);
    }

    /**
     * 获取字符串长度
     */
    public static int getStringLength(String str) {
        return str == null ? 0 : str.length();
    }
}